package cc.ttiot.service.dataCollection.serial;

import com.pi4j.io.serial.*;
import com.serotonin.modbus4j.serial.SerialPortWrapper;

import java.io.InputStream;
import java.io.OutputStream;

import static com.pi4j.io.serial.RaspberryPiSerial.DEFAULT_COM_PORT;

/**
 * @Description: SerialPortWrapper的实现类，提供获取串口开、关、输入、输出流的部分方法
 * @Author :
 * @Version :
 * @Date :
 */
public class SerialPortWrapperImpl implements SerialPortWrapper {
    //
    private final Serial serial;

    /**
     * 默认配置:
     * "--device (device-path)"                   [DEFAULT: /dev/ttyAMA0]
     * "--baud (baud-rate)"                       [DEFAULT: 9600]
     * "--data-bits (5|6|7|8)"                    [DEFAULT: 8]
     * "--parity (none|odd|even)"                 [DEFAULT: none]
     * "--stop-bits (1|2)"                        [DEFAULT: 1]
     * "--flow-control (none|hardware|software)"  [DEFAULT: none]
     */
    protected SerialConfig serialConfig;

    {
        //创建串口实例
        serial = SerialFactory.createInstance();

        //串口默认配置初始化
        serialConfig = new SerialConfig();
    }
    public SerialPortWrapperImpl() {
        super();
    }

    public SerialPortWrapperImpl(SerialConfig serialConfig) {
        this.serialConfig = serialConfig;
    }

    @Override
    public void close() throws Exception {
        serial.close();
    }

    @Override
    public void open() throws Exception {
        serial.open(serialConfig);
    }

    @Override
    public InputStream getInputStream() {
        return serial.getInputStream();
    }

    @Override
    public OutputStream getOutputStream() {
        return serial.getOutputStream();
    }

    @Override
    public int getBaudRate() {
        return serialConfig.baud().getValue();
    }

    @Override
    public int getDataBits() {
        return serialConfig.dataBits().getValue();
    }

    @Override
    public int getStopBits() {
        return serialConfig.stopBits().getValue();
    }

    @Override
    public int getParity() {
        return serialConfig.parity().getIndex();
    }
}
